package com.glsc.ngateway.ldap.controller;


import com.alibaba.fastjson.JSON;
import com.glsc.ngateway.common.api.common.enums.GatewayConstant;
import com.glsc.ngateway.common.api.common.utils.DateUtil;
import com.glsc.ngateway.common.api.common.utils.encrypt.RSAEncrypt;
import com.glsc.ngateway.common.api.ldap.dto.*;
import com.glsc.ngateway.common.api.ldap.enums.MessageEum;
import com.glsc.ngateway.common.api.ldap.resp.InterfaceReponse;
import com.glsc.ngateway.common.api.ldap.resp.LdapResponse;
import com.glsc.ngateway.ldap.enums.CheckInterfaceParamsInterfaceIdEnum;
import com.glsc.ngateway.ldap.enums.CheckLoginStatuEnum;
import com.glsc.ngateway.ldap.exception.BusinessException;
import com.glsc.ngateway.ldap.service.*;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.google.code.kaptcha.util.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import smartbi.sdk.ClientConnector;
import smartbi.sdk.service.user.UserManagerService;
import smartbi.user.IDepartment;
import smartbi.user.IRole;
import smartbi.user.IUser;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;


/**
 * @Title: FlowWorkController
 * @Description: Controller
 * @author: 张宁
 * @version: 1.0.0
 * @date: 2020/12/21 16:29
 */


@RestController
@RequestMapping("/ldapUser")
public class LdapLoginController {

    @Value("${sign.secretkey}")
    private String secretkey;

    @Autowired
    private LdapLoginService ldapLoginService;  // ldap服务

    @Resource
    private LdapEhrDeptService ldapEhrDeptService;

    @Resource
    private LdapEhrEmpService ldapEhrEmpService;

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    private HttpServletRequest request;

    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Value("${smartbi.url}")
    private String smartbi_url = "";

    @Value("${smartbi.username}")
    private String smartbi_username = "";

    @Value("${smartbi.password}")
    private String smartbi_password = "";

    @Value("${smartbi.webUserPassword}")
    private String smartbi_webUserPassword = "";

    @Value("${smartbiv10.url}")
    private String smartbiv10_url = "";

    @Value("${smartbiv10.username}")
    private String smartbiv10_username = "";

    @Value("${smartbiv10.password}")
    private String smartbiv10_password = "";

    @Value("${smartbiv10.webUserPassword}")
    private String smartbiv10_webUserPassword = "";

    @Resource
    private LdapUserFlowService ldapUserFlowService;

    @Resource
    private ValidateCodeService validateCodeService;
    /**
     * @param
     * @return
     * @description 更新systemId
     */
    @RequestMapping(method = RequestMethod.GET, value = "/getsystem")
    public String getsystem(@RequestParam("department") String department,
                            @RequestParam(value = "companyName", required = false) String companyName) {
        String sys = ldapEhrDeptService.getSystemIdByDepartment(department,companyName);
        return JSON.toJSONString(InterfaceReponse.returnSuccss(sys));
    }

    @Autowired
    public void setRequest(HttpServletRequest request) {
        this.request = request;
    }

    @PostMapping("/getOaUserToken")
    public String getOaUserToken(@RequestBody LdapUserDto ldapUserDto) {
        logger.info("生成oa用户token,用户名=" + ldapUserDto.getUserName() + "系统=" + ldapUserDto.getSystemId() + ",时间=" + DateUtil.getCurrentDate(DateUtil.formatMillisecond));

        if ((StringUtils.isEmpty(ldapUserDto.getTryCode()) || (!ldapUserDto.getTryCode().equals(secretkey)))) {
            return JSON.toJSONString(InterfaceReponse.returnError("getOaUserToken密钥验证失败"));
        }
        if (ldapLoginService.checkOaUser(ldapUserDto.getUserName())) {
            logger.info("完成oa用户认证:" + ldapUserDto.getUserName() + "系统为：" + ldapUserDto.getSystemId() + ",时间为：" + DateUtil.getCurrentDate(DateUtil.formatMillisecond));
            TokenMapDto tokenMap = ldapLoginService.getUserToken(ldapUserDto.getUserName(), ldapUserDto.getSystemId());
            return JSON.toJSONString(InterfaceReponse.returnSuccss(tokenMap));
        } else {
            return JSON.toJSONString(InterfaceReponse.returnError("oa用户认证失败"));
        }
    }

    /**
     * @param ldapUserDto
     * @return
     * @throws IOException
     * @description 用戶登录验证
     */
    @PostMapping("/login")
    public String login(@RequestBody LdapUserDto ldapUserDto) throws Exception {
        logger.info("接受用户登录验证,用户名=" + ldapUserDto.getUserName() + ",passwd=" + ldapUserDto.getPassword() + ",时间=" + DateUtil.getCurrentDate(DateUtil.formatMillisecond));


        if (CheckInterfaceParamsInterfaceIdEnum.LOGIN_CODE.check(ldapUserDto)) {
            String password = RSAEncrypt.decrypt(ldapUserDto.getPassword(), GatewayConstant.RSA_PRIVATE_KEY);
            CheckLoginStatuEnum authorityResult = ldapLoginService.checkLogin(ldapUserDto.getUserName(), password);
            logger.info("完成Ldap认证,用户名=" + ldapUserDto.getUserName() + ",passwd=" + ldapUserDto.getPassword() + ",时间=" + DateUtil.getCurrentDate(DateUtil.formatMillisecond));
            if (CheckLoginStatuEnum.SUCCESS.equals(authorityResult)) {
                TokenMapDto tokenMap = ldapLoginService.getUserToken(ldapUserDto.getUserName(), ldapUserDto.getSystemId());
                logger.info("获取用户token,用户名=" + ldapUserDto.getUserName() + ",passwd=" + ldapUserDto.getPassword() + ",时间=" + DateUtil.getCurrentDate(DateUtil.formatMillisecond));
                return JSON.toJSONString(InterfaceReponse.returnSuccss(tokenMap));
            } else if (CheckLoginStatuEnum.PASSWORD_WRONG.equals(authorityResult)) {
                return JSON.toJSONString(InterfaceReponse.returnException("用户密码错误"));
            } else {
                return JSON.toJSONString(InterfaceReponse.returnError("用户不存在"));
            }
        } else {
            return JSON.toJSONString(InterfaceReponse.returnError("缺失必要参数"));
        }
    }

    /**
     * 获取秘钥
     */
    @GetMapping("/getRSAPublicKey")
    public String getKey() {
        return GatewayConstant.RSA_PUBLIC_KEY;
    }

    @PostMapping("/loginPortal")
    public InterfaceReponse<TokenMapDto> loginPortal(@RequestBody LdapUserDto ldapUserDto) throws Exception {
        logger.info("接受用户登录验证,用户名=" + ldapUserDto.getUserName() + ",passwd=" + ldapUserDto.getPassword() + ",时间=" + DateUtil.getCurrentDate(DateUtil.formatMillisecond));
        String rightCode = (String) request.getSession().getAttribute("rightCode");
        String tryCode = ldapUserDto.getTryCode();
        if (StringUtils.isEmpty(rightCode) || StringUtils.isEmpty(tryCode) || !rightCode.equals(tryCode)) {
            return InterfaceReponse.returnError("验证码错误");
        }
        return loginWithoutCode(ldapUserDto);
    }

    @PostMapping(value = "/loginWithoutCode", produces = {"application/json"})
    public InterfaceReponse<TokenMapDto> loginWithoutCode(@RequestBody LdapUserDto ldapUserDto) throws Exception {
        logger.info("接受用户登录验证,用户名=" + ldapUserDto.getUserName() + ",passwd=" + ldapUserDto.getPassword() + ",时间=" + DateUtil.getCurrentDate(DateUtil.formatMillisecond));
        if (CheckInterfaceParamsInterfaceIdEnum.LOGIN_PORTAL_CODE.check(ldapUserDto)) {
            String password = RSAEncrypt.decrypt(ldapUserDto.getPassword(), GatewayConstant.RSA_PRIVATE_KEY);
            CheckLoginStatuEnum authorityResult = ldapLoginService.checkLogin(ldapUserDto.getUserName(), password);
            logger.info("完成Ldap认证,用户名=" + ldapUserDto.getUserName() + ",passwd=" + ldapUserDto.getPassword() + ",时间=" + DateUtil.getCurrentDate(DateUtil.formatMillisecond));
            switch (authorityResult) {
                case SUCCESS:
                    return InterfaceReponse.returnSuccss(ldapLoginService.getTokenMap(ldapUserDto.getUserName(), ldapUserDto.getSystemId()));
                case LOCK:
                    return InterfaceReponse.returnException("账号锁定，请联系OA管理员：苏伟解锁账号。");
                case PASSWORD_WRONG:
                    return InterfaceReponse.returnException("用户密码错误");
                default:
                    return InterfaceReponse.returnError("用户不存在");
            }
        } else {
            return InterfaceReponse.returnError("缺失必要参数");
        }
    }

    @PostMapping("/loginPortalForOa")
    public String loginPortal(@RequestBody OaParamDto oaParamDto) {
        Assert.notNull(oaParamDto, "参数不存在");
        logger.info("接受用户登录验证,用户名=" + oaParamDto.getUserName() + ",timesign=" + oaParamDto.getTimeSign() + ",vaildCode=" + oaParamDto.getVaildCode() + ",时间=" + DateUtil.getCurrentDate(DateUtil.formatMillisecond));

        try {
            Assert.hasLength(oaParamDto.getUserName(), "用户名不存在");
            //由服务器端校验时加上时间
//            Assert.hasLength(oaParamDto.getTimeSign(),"时间戳不存在");
//            LocalDate dateParam = getLocalDate_yyyyMMdd_(oaParamDto.getTimeSign());
//            Assert.notNull(dateParam,"时间格式不正确");
//            if (dateParam.compareTo(LocalDate.now()) != 0){//不等于今天
//                throw new IllegalArgumentException("认证过期，请刷新后重新进入");
//            }
            Assert.hasLength(oaParamDto.getVaildCode(), "校验码不存在");
        } catch (IllegalArgumentException e) {
            return JSON.toJSONString(InterfaceReponse.returnError(e.getMessage()));
        }

        try {
            CheckLoginStatuEnum authorityResult = ldapLoginService.checkLoginPortalForOa(oaParamDto);
            logger.info("完成Ldap认证,用户名=" + oaParamDto.getUserName() + ",时间=" + DateUtil.getCurrentDate(DateUtil.formatMillisecond));
            if (CheckLoginStatuEnum.SUCCESS.equals(authorityResult)) {
                return JSON.toJSONString(InterfaceReponse.returnSuccss(ldapLoginService.getTokenMap(oaParamDto.getUserName(), null)));
            } else if (CheckLoginStatuEnum.USER_NOT_EXIST.equals(authorityResult)) {
                return JSON.toJSONString(InterfaceReponse.returnException("用户错误"));
            } else {
                return JSON.toJSONString(InterfaceReponse.returnError("异常"));
            }
        } catch (Exception e) {
            return JSON.toJSONString(InterfaceReponse.returnError("其他异常"));
        }

    }

    /**
     * @param ldapUserDto
     * @return
     * @description 验证Token
     */
    @RequestMapping(method = RequestMethod.POST, value = "/checkToken")
    public String checkToken(@RequestBody LdapUserDto ldapUserDto) throws Exception {
        logger.info("token验证，token=" + ldapUserDto.getToken() + ",系统ID=" + ldapUserDto.getSystemId() + "时间=" + DateUtil.getCurrentDate(DateUtil.formatSecond));
        if (CheckInterfaceParamsInterfaceIdEnum.CHECK_TOKEN.check(ldapUserDto)) {
            Map<String, String> dataMap = ldapLoginService.checkTokenValid(ldapUserDto.getToken(), ldapUserDto.getSystemId(), ldapUserDto.getUserName());
            if (dataMap.get("userName").equals(GatewayConstant.TOKEN_OVERDUE)) {
                return JSON.toJSONString(InterfaceReponse.returnException("Token 失效或者Token不存在"));
            } else {
                return JSON.toJSONString(InterfaceReponse.returnSuccss(dataMap));
            }
        } else {
            return JSON.toJSONString(InterfaceReponse.returnError("缺失必要参数"));
        }
    }

    /**
     * @param ldapUserDto
     * @return
     * @description 验证Token 并返回 OAToken
     */
    @RequestMapping(method = RequestMethod.POST, value = "/checkTokenAndReturnOaToken")
    public LdapResponse checkTokenAndReturnOaToken(@RequestBody LdapUserDto ldapUserDto) throws Exception {
        logger.info("token验证，token=" + ldapUserDto.getToken() + ",系统ID=" + ldapUserDto.getSystemId() + ",用户ID=" + ldapUserDto.getUserName() + "时间=" + DateUtil.getCurrentDate(DateUtil.formatSecond));
        if (CheckInterfaceParamsInterfaceIdEnum.CHECK_TOKEN.check(ldapUserDto)) {
            Map<String, String> dataMap = ldapLoginService.checkTokenValid(ldapUserDto.getToken(), ldapUserDto.getSystemId(), ldapUserDto.getUserName());
            logger.info("ldap校验token结果:{}", dataMap);
            if (dataMap.get("userName").equals(GatewayConstant.TOKEN_OVERDUE)) {
                return LdapResponse.error("Token 失效或者Token不存在");
            } else if (dataMap.get("userName").equals(ldapUserDto.getUserName())) {
                String oaToken = ldapLoginService.getOaToken(ldapUserDto.getUserName());
                logger.info("获取oaToken=" + oaToken);
                return LdapResponse.success(oaToken);
            } else {
                return LdapResponse.error("解析token获取用户名有异常,用户不一致!");
            }
        } else {
            return LdapResponse.error("缺失必要参数,请检查token,systemid,username");
        }
    }

    /**
     * @param ldapUserDto
     * @return
     * @description 更新systemId
     */
    @RequestMapping(method = RequestMethod.POST, value = "/updateSystemId")
    public String updateSystemId(@RequestBody LdapUserDto ldapUserDto) {
        logger.info("更新systemId，token=" + ldapUserDto.getToken() + ",系统ID=" + ldapUserDto.getSystemId() + "时间=" + DateUtil.getCurrentDate(DateUtil.formatSecond));
        ldapUserFlowService.updateSystemId(ldapUserDto.getSystemId(), ldapUserDto.getToken());
        return JSON.toJSONString(InterfaceReponse.returnSuccss("更新systemId成功"));
    }

    /**
     * @param ldapUserDto
     * @return
     * @description 验证Token
     */
    @RequestMapping(method = RequestMethod.POST, value = "/renewTokenExpire")
    public String renewTokenExpire(@RequestBody LdapUserDto ldapUserDto) throws Exception {
        logger.info("token验证，token=" + ldapUserDto.getToken() + ",顺延时间=" + ldapUserDto.getDelayHours() + "时间=" + DateUtil.getCurrentDate(DateUtil.formatSecond));
        if (CheckInterfaceParamsInterfaceIdEnum.RENEW_TOKEN.check(ldapUserDto)) {
            Map<String, String> dataMap = ldapLoginService.checkTokenValid(ldapUserDto.getToken(), ldapUserDto.getSystemId());
            if (dataMap.get("userName").equals(GatewayConstant.TOKEN_OVERDUE)) {
                return JSON.toJSONString(InterfaceReponse.returnException("顺延失败，Token 失效或者Token不存在"));
            } else {
                ldapLoginService.delayExpireTime(ldapUserDto.getToken(), ldapUserDto.getDelayHours(), ldapUserDto.getSystemId());
                return JSON.toJSONString(InterfaceReponse.returnSuccss("token 延时成功"));
            }
        } else {
            return JSON.toJSONString(InterfaceReponse.returnError("缺失必要参数"));
        }

    }

    @RequestMapping(method = RequestMethod.GET, value = "/getExpireTime")
    public String getExpireTime(@RequestParam("token") String token) {
        String time = ldapLoginService.getExpireTime(token);
        return JSON.toJSONString(InterfaceReponse.returnSuccss(time));
    }

    /**
     * @param ldapUserDto
     * @return
     * @description 验证Token
     */
    @RequestMapping(method = RequestMethod.POST, value = "/kickOutToken")
    public String kickOutToken(@RequestBody LdapUserDto ldapUserDto) {
        logger.info("踢出用户token，token=" + ldapUserDto.getToken() + ",系统ID=" + ldapUserDto.getSystemId() + "时间=" + DateUtil.getCurrentDate(DateUtil.formatSecond));
        if (CheckInterfaceParamsInterfaceIdEnum.KICKOUT_TOKEN.check(ldapUserDto)) {
            Boolean kickOutFlag = ldapLoginService.kickoutToken(ldapUserDto.getToken(), ldapUserDto.getSystemId());
            if (kickOutFlag) {
                return JSON.toJSONString(InterfaceReponse.returnSuccss("Token删除成功"));
            } else {
                return JSON.toJSONString(InterfaceReponse.returnException("Token不存在，或者失效"));
            }
        } else {
            return JSON.toJSONString(InterfaceReponse.returnError("缺失必要参数"));
        }

    }


    @PostMapping("/checkUsrStatus")
    public String checkUsrStatus(@RequestBody Map<String, Object> userMap) throws Exception {

        logger.info("查询用户状态，入参=" + userMap.toString() + ",查询时间=" + DateUtil.getCurrentDate(DateUtil.formatMillisecond));
        if (!(userMap.containsKey("token") && userMap.containsKey("systemId") && userMap.containsKey("users"))) {
            throw new BusinessException(MessageEum.EXCEPTION.getCode(), "接口参数问题，请填写必要参数");
        } else {
            Map<String, String> map = ldapLoginService.checkTokenValid(userMap.get("token").toString(), userMap.get("systemId").toString());
            if (map.get(GatewayConstant.LDAP_USER_NAME).equals(GatewayConstant.TOKEN_OVERDUE)) {
                throw new BusinessException(MessageEum.EXCEPTION.getCode(), "token 已经过期或者token不存在，请填写正确token");
            }
            if (userMap.get(GatewayConstant.LDAP_USER_NAME).toString().split(",").length > GatewayConstant.LIST_LIMIT) {
                throw new BusinessException(MessageEum.EXCEPTION.getCode(), "批量查询用户名称数目太多，请减少查询数目");
            }
        }
        logger.info("完成批量查询接口必要条件校验，" + ",完成时间=" + DateUtil.getCurrentDate(DateUtil.formatMillisecond));
        String[] usrArr = userMap.get("users").toString().split(",");
        List<Map<String, Object>> dataList = ldapEhrEmpService.returnUserStatus(usrArr);
        logger.info("完成用户状态批量查询" + ",完成时间=" + DateUtil.getCurrentDate(DateUtil.formatMillisecond));
        return JSON.toJSONString(InterfaceReponse.returnSuccss(dataList));


    }


    /**
     * 2、生成验证码
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @throws Exception
     */
    @RequestMapping("/defaultKaptcha")
    public void defaultKaptcha(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
            throws Exception {

        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        Map<String,String> randomValue = validateCodeService.getRandom();
        try {
            // 生产验证码字符串并保存到session中
            String createText = randomValue.get("redisStr");
            httpServletRequest.getSession().setAttribute("rightCode", createText);
            // 使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = validateCodeService.getImage(randomValue.get("randomStr"));
            ImageIO.write(challenge, "png", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    /**
     * 3、校对验证码
     *
     * @param httpServletRequest
     * @param httpServletResponse
     * @return
     */
    @RequestMapping("/imgvrifyControllerDefaultKaptcha")
    public InterfaceReponse imgvrifyControllerDefaultKaptcha(HttpServletRequest httpServletRequest,
                                                             HttpServletResponse httpServletResponse) {

        try {
            String rightCode = (String) httpServletRequest.getSession().getAttribute("rightCode");
            String tryCode = httpServletRequest.getParameter("tryCode");
            logger.info("rightCode:" + rightCode + " ———— tryCode:" + tryCode);
            if (StringUtils.isEmpty(rightCode) || StringUtils.isEmpty(tryCode) || !rightCode.equals(tryCode)) {
                return InterfaceReponse.returnException("错误的验证码");
            } else {
                return InterfaceReponse.returnSuccss("验证成功");
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return InterfaceReponse.returnException(e.getMessage());
        }
    }

    /*
     * OA用户登录时往SmartBI系统同步用户信息
     * 1.
     * 2. 如果该OA用户已经在smartBI系统里存在了，检查role，添加role
     *
     * */
    @PostMapping("/syncBIUser")
    public InterfaceReponse syncBIUser(@RequestBody Map<String, String> userMap) {
        logger.info("开始同步BI用户信息，入参={},查询时间={}", userMap.toString(), DateUtil.getCurrentDate(DateUtil.formatMillisecond));

        String username = userMap.get("username");
        String systemId = userMap.get("systemId");

        //需要同步的系统用户列表，TODO 改为配置，20230505 zzp
        List<String> syncBISystemList = Arrays.asList(
                "glrms", "glsubsidiary",
                "glscdata", "glgsdata",
                "glam", "glamrisk",
                "fundinvest",
                "glmetadata",
                "opmanage");
        if (!syncBISystemList.contains(systemId)) {//不要同步用户的系统
            logger.info("不需同步该用户至BI");
            return InterfaceReponse.returnSuccss("");
        }
        //去除ADMIN账号，此处代码未发现对逻辑的影响
        if ("admin".equals(username)) {
            logger.info("不需同步该用户至BI");
            return InterfaceReponse.returnSuccss("");
        }

        //只有风控还需要使用V9，即使不成功，也不影响整个结果
        if("glrms".equalsIgnoreCase(systemId)){
            try{
                InterfaceReponse interfaceResponseV9 = syncBiUser(systemId, "v9", username, smartbi_url, smartbi_username, smartbi_password, smartbi_webUserPassword);

                if (interfaceResponseV9.getCode() == MessageEum.SUCCESS.getCode()){
                    logger.info("同步用户信息至BIv9成功");
                }else{
                    logger.info("同步用户信息至BIv9失败");
                }

            }catch (Exception e) {
                logger.info("同步用户信息至BIv9失败");
            }
        }

        //同步用户至V10
        try {
            // Sync user to smartbi v10
            InterfaceReponse interfaceResponseV10 = syncBiUser(systemId, "v10", username, smartbiv10_url, smartbiv10_username, smartbiv10_password, smartbiv10_webUserPassword);
            if (interfaceResponseV10.getCode() == MessageEum.SUCCESS.getCode()){
                logger.info("同步用户信息至BIv10成功");
                return InterfaceReponse.returnSuccss("成功同步用户信息至BIv10");
            }else{
                logger.info("同步用户信息至BIv10失败");
                return InterfaceReponse.returnException(interfaceResponseV10.getMessage());
            }

        }catch (Exception e) {
            logger.info("同步用户信息至BIv10失败");
            return InterfaceReponse.returnException(e.getMessage());
        }




//        // Sync user to smartbi v9
//        InterfaceReponse interfaceResponseV9 = syncBiUser(systemId, "v9", username, smartbi_url, smartbi_username, smartbi_password, smartbi_webUserPassword);
//        InterfaceReponse interfaceResponseV10 = syncBiUser(systemId, "v10", username, smartbiv10_url, smartbiv10_username, smartbiv10_password, smartbiv10_webUserPassword);
//
//        if (interfaceResponseV9.getCode() == MessageEum.SUCCESS.getCode() && interfaceResponseV10.getCode() == MessageEum.SUCCESS.getCode()) {
//                logger.info("成功同步用户信息至BIv9和v10");
//                return InterfaceReponse.returnSuccss("成功同步用户信息至BIv9和v10");
//            } else if (!(interfaceResponseV9.getCode() == MessageEum.SUCCESS.getCode())) {
//                return InterfaceReponse.returnException(interfaceResponseV9.getMessage());
//            } else {
//                return InterfaceReponse.returnException(interfaceResponseV10.getMessage());
//            }
//        } catch (Exception e) {
//            return InterfaceReponse.returnException(e.getMessage());
//        }

    }

    private InterfaceReponse syncBiUser(String systemId, String biVersion, String username, String biUrl, String biUsername, String biPassword, String webDefaultPassword) throws Exception {
        ClientConnector conn = new ClientConnector(biUrl);

        try {
            logger.info("开始连接BI, 版本:{}, 用户名:{},密码{}", biVersion, biUsername, biPassword);
            boolean con = conn.open(biUsername, biPassword);
            if (con) {
                logger.info("连接BI, 版本：{} 成功", biVersion);
                UserManagerService userManagerService = new UserManagerService(conn);
                IUser user = userManagerService.getUserByName(username);

                //如果该OA用户在smartBI中不存在，则创建用户，并加入本系统对应的组(department),每个组有默认的web角色。
                if (user == null) {
                    //{"departmentCode":"glam","name":"glam","alias":"glam","id":"Iff8080810176dfe6dfe65fb90176efdd74621699","desc":""}
                    IDepartment department = null;
                    if ("glrms".equalsIgnoreCase(systemId)) {
                        department = userManagerService.getDepartmentByName("trm");
                    } else if ("glscdata".equalsIgnoreCase(systemId) || "glgsdata".equalsIgnoreCase(systemId)) {
                        department = userManagerService.getDepartmentByName("glsc");
                    } else if ("glsubsidiary".equalsIgnoreCase(systemId)) {
                        department = userManagerService.getDepartmentByName("glsubs");
                    } else if ("glam".equalsIgnoreCase(systemId) || "glamrisk".equalsIgnoreCase(systemId)){
                        department = userManagerService.getDepartmentByName("glam");
                    }else if ("fundinvest".equalsIgnoreCase(systemId)) {
                        department = userManagerService.getDepartmentByName("fundinvest");
                    }else if ("opmanage".equalsIgnoreCase(systemId)) {
                        department = userManagerService.getDepartmentByName("glop");
                    } else if("glmetadata".equalsIgnoreCase(systemId)){
                        department = userManagerService.getDepartmentByName("glmetadata");
                    }else {
                        department = userManagerService.getDepartmentByName("others");
                    }

                    if (department == null) {
                        logger.info("为用户{}在smartBI创建账号失败，所属系统{}没有对应的department{}", username, systemId, department.getName());
                    }
                    String ret = userManagerService.createUser(department.getId(), username, "", "", webDefaultPassword, true);
                    logger.info("为用户{}在smartBI创建账号，所属department为{}", username, department);
                } else {
                    List<? extends IRole> roles = userManagerService.getAllRolesOfUser(user.getId());
                    List<String> roleidList = roles.stream().map(IRole::getId).collect(Collectors.toList());
                    List<String> rolenameList = roles.stream().map(IRole::getName).collect(Collectors.toList());
                    if ("glrms".equalsIgnoreCase(systemId)  && !rolenameList.contains("trm_web")) {
                        IRole role = userManagerService.getRoleByName("trm_web");
                        roleidList.add(role.getId());
                        userManagerService.assignRolesToUser(user.getId(), roleidList);
                        logger.info("为用户{}在smartBI添加role：{}", username, role.getName());
                    }
                    if (("glscdata".equalsIgnoreCase(systemId) || "glgsdata".equalsIgnoreCase(systemId)) && !rolenameList.contains("glsc_web")) {
                        IRole role = userManagerService.getRoleByName("glsc_web");
                        roleidList.add(role.getId());
                        userManagerService.assignRolesToUser(user.getId(), roleidList);
                        logger.info("为用户{}在smartBI添加role：{}", username, role.getName());
                    }
                    if (("glam".equalsIgnoreCase(systemId) || "glamrisk".equalsIgnoreCase(systemId))
                            && !rolenameList.contains("glam_web")) {
                        IRole role = userManagerService.getRoleByName("glam_web");
                        roleidList.add(role.getId());
                        userManagerService.assignRolesToUser(user.getId(), roleidList);
                        logger.info("为用户{}在smartBI添加role：{}", username, role.getName());
                    }
                    if ("fundinvest".equalsIgnoreCase(systemId)  && !rolenameList.contains("fundinvest_web")) {
                        IRole role = userManagerService.getRoleByName("fundinvest_web");
                        roleidList.add(role.getId());
                        userManagerService.assignRolesToUser(user.getId(), roleidList);
                        logger.info("为用户{}在smartBI添加role：{}", username, role.getName());
                    }
                    if ("glsubsidiary".equalsIgnoreCase(systemId) && !rolenameList.contains("glsubs_web")) {
                        IRole role = userManagerService.getRoleByName("glsubs_web");
                        roleidList.add(role.getId());
                        userManagerService.assignRolesToUser(user.getId(), roleidList);
                        logger.info("为用户{}在smartBI添加role：{}", username, role.getName());
                    }
                    if ("glmetadata".equalsIgnoreCase(systemId) && !rolenameList.contains("glmeta_data_web")) {
                        IRole role = userManagerService.getRoleByName("glmeta_data_web");
                        roleidList.add(role.getId());
                        userManagerService.assignRolesToUser(user.getId(), roleidList);
                        logger.info("为用户{}在smartBI添加role：{}", username, role.getName());
                    }
                    if ("opmanage".equalsIgnoreCase(systemId) && !rolenameList.contains("glop_web")) {
                        IRole role = userManagerService.getRoleByName("glop_web");
                        roleidList.add(role.getId());
                        userManagerService.assignRolesToUser(user.getId(), roleidList);
                        logger.info("为用户{}在smartBI添加role：{}", username, role.getName());
                    }
                }
            }

            logger.info("同步BI用户信息完成, BI版本: {}" + biVersion + ",完成时间={}" + DateUtil.getCurrentDate(DateUtil.formatMillisecond));
            return InterfaceReponse.returnSuccss("验证成功");
        } catch (Exception e) {
            return InterfaceReponse.returnException("BI版本:" + biVersion + e.getMessage());
        } finally {
            conn.close();
        }
    }

    @RequestMapping(method = RequestMethod.POST, value = "/checkWorkWechatToken")
    public LdapResponse<LdapWorkWechatTokenCheckResultDto> checkWorkWechatToken(@RequestBody LdapWorkWechatTokenCheckParamDto param) {
        String zzpToken = "cbI/Qv1Zsgs9d6R6HUSFacnHecsIc7rzOihiNCxtQ+Wxnw29rszUwQ2Y9kX1xAu8iC823Rdfkr1zKAB4dfJvyDidBnR2yYHPmbKUd9Lj9dhb9x60xHvFFkmeI++F49pENf/Xtco6lHXUzk6cYZ6kEzupjV5lGuZLK30Fvxhu1kRRx8bNDnbUfwAWAVWurp+0Ra69APzucsLQQnAwmC3j1S6USw==";
        String qywxLoginToken = param.getToken();
        if (zzpToken.equals(qywxLoginToken)) {
            LdapWorkWechatTokenCheckResultDto resultDto = new LdapWorkWechatTokenCheckResultDto();
            resultDto.setCreateTime("2023-11-10 13:06:03");
            resultDto.setOa_account("zzp");
            resultDto.setOa_name("周志鵬");
            resultDto.setUni_account_no("3");
            resultDto.setUni_account_no("zzp");

            return LdapResponse.success(resultDto);
        }

        LdapWorkWechatTokenCheckResultDto resultDto = ldapLoginService.checkWorkWechatToken(param.getToken());

        if (resultDto != null) {
            return LdapResponse.success(resultDto);
        } else {
            return LdapResponse.error("登录失败，请检查token是否正确");
        }
    }

}
